package com.xmjs.baselibrary.utils;

import com.xmjs.baselibrary.base.IBaseView;
import com.xmjs.baselibrary.network.retrofit.RxUtil;

import io.reactivex.Observable;
import io.reactivex.subjects.PublishSubject;
import io.reactivex.subjects.Subject;

/**
 * RxBus工具类
 */
public class RxBus {
    private volatile static RxBus mDefaultInstance;
    private final Subject<Object> mBus;

    private RxBus() {
        mBus = PublishSubject.create().toSerialized();
    }

    /**
     * 构造单例
     *
     * @return
     */
    public static RxBus getInstance() {
        if (mDefaultInstance == null) {
            synchronized (RxBus.class) {
                if (mDefaultInstance == null) {
                    mDefaultInstance = new RxBus();
                }
            }
        }
        return mDefaultInstance;
    }

    /**
     * 发送事件
     *
     * @param event
     */
    public void post(Object event) {
        mBus.onNext(event);
    }

    /**
     * 观察事件
     *
     * @param view  观察者
     * @param event 事件
     * @param <T>
     * @return 根据传递的event事件返回特定类型的被观察者
     */
    public <T> Observable<T> toObservable(IBaseView view, final Class<T> event) {
        return mBus.ofType(event).compose(RxUtil.bindToLifecycle(view)).compose(RxUtil.applySchedulers());
    }

    /**
     * 判断是否有订阅者
     */
    public boolean hasObservers() {
        return mBus.hasObservers();
    }
}
